<?php

declare(strict_types=1);

namespace App\Job;

use App\Model\Message;
use App\Model\UserProfile;
use App\Model\UserRecOnline;
use Hyperf\AsyncQueue\Job;

class PushOnlineTipJob extends Job
{
    /**
     * 参数
     */
    public $params;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     *
     * @var int
     */
    protected $maxAttempts = 1;

    public function __construct($params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        $userId = $this->params['user_id'] ?? 0;
        if (!$userId) return;
        $this->doPush($userId, $this->params['profile']);
        log_user_result($userId, ($this->params['profile'])->nick_name);
        return;
    }

    function doPush($userId = 0, $profile = null)
    {
        $onlineHostIds = UserProfile::getOnlineUsers(UserProfile::ROLE_HOST, 100);
        //没有当前在线的人
        if (!$onlineHostIds) return false;

        //该用户当天已经推过N次的主播（N配置）
        $pushedHostIds = check_dev_env() ? [] : UserRecOnline::getPushedHostIds($userId, 3);
        $pushedHostIds[] = $userId;

        //已经推过的去重
        $onlineHostIds = array_values(array_diff($onlineHostIds, $pushedHostIds));
        //没有当前在线的人
        if (!$onlineHostIds) return false;

        //选择10个
        shuffle($onlineHostIds);
        shuffle($onlineHostIds);
        $onlineHostIds = array_slice($onlineHostIds, 0, 6);
        //发送透传消息
        $msg = [
            'user_id' => $userId,
            'nick_name' => $profile->nick_name,
            'avatar' => $profile->avatar,
            'gender' => $profile->gender,
            'age' => $profile->age,
            'rich_value' => $profile->rich_value,
        ];
        Message::sendSlient($onlineHostIds, 'ONLINE_TIP', $msg);

        //添加推荐记录
        array_walk($onlineHostIds, function ($onlineHostId) use ($userId) {
            UserRecOnline::addRecUser($onlineHostId, $userId);
        });

        //日志
        log_user_result($userId, "OnlineHosts:" . json_encode($onlineHostIds) . "==PushedHosts:" . count($pushedHostIds));
    }
}
